<template>
<div>
<script id="editor" :name="name" type="text/plain">

</script>

</div>
</template>

<script>
import "../../www/static/plugins/ueditor/ueditor.config.js";
import "../../www/static/plugins/ueditor/ueditor.all.js";
import "../../www/static/plugins/ueditor/lang/zh-cn/zh-cn.js";
import "../../www/static/plugins/ueditor/ueditor.parse.js";
import { fail } from 'assert';

export default {
    name: "ueditor",
    props: ["name", "content", "config", "toolbar"],
    data: function() {
        return {
            editor: null,
            editorConfig: {
                allowDivTransToP: false,
                serverUrl: Config.WebSiteApiUrl + '/base/ueditor/control',
                pasteplain: false,
                iframeCssUrl: "/static/plugins/ueditor/themes/iframe.css",
                allHtmlEnabled: true,
                catchRemoteImageEnable: false,
                initialFrameWidth: null,
                initialFrameHeight: 400,
                autoHeightEnabled:true,//是否自动长高
                zIndex:900,//编辑器层级的基数,默认是900
                enableAutoSave:true,//启用自动保存
                autoFloatEnabled:false,
                //topOffset: 50,
                webAppKey: "", //百度应用的APIkey
            },
            PreLastExistImg: [],
            RemovedImgList: []
        };
    },
    mounted: function() {
        let self = this;
        if (this.config) {
            for (var key in this.config) {
                this.editorConfig[key] = this.config[key];
            }
        }
        var toolbarsComplate = [
            [
                'fullscreen', 'source', '|', 'undo', 'redo', '|',
                'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
                'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                'directionalityltr', 'directionalityrtl', 'indent', '|',
                'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
                'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
                'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
                'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
                'print', 'preview', 'searchreplace', 'drafts', 'help'
            ]
        ];
        var toolbarsMini = [
            [
                "forecolor",
                "justifyleft",
                "justifycenter",
                "justifyright",
                "blockquote",
                "|",
                "insertunorderedlist",
                "insertorderedlist",
                "|",
                "unlink",
                "link",
                "|",
                "insertimage",
                "snapscreen",
                "map",
                "inserttable",
                "|",
                "emotion"
            ]
        ];
        var toolbarsNormal = [
            [
                "emotion",
                "undo",
                "redo",
                "|",
                "forecolor",
                "justifyleft",
                "justifycenter",
                "justifyright",
                "blockquote",
                "|",
                "insertunorderedlist",
                "insertorderedlist",
                "|",
                "unlink",
                "link",
                "|",
                "insertimage",
                "insertvideo",
                "music",
                "map",
                "inserttable"
            ]
        ];

        if (!this.toolbar) this.toolbar = "normal";
        switch (this.toolbar) {
            case "complate":
                this.editorConfig.toolbars = toolbarsComplate;
                break;
            case "mini":
                this.editorConfig.toolbars = toolbarsMini;
                break;
            case "normal":
                this.editorConfig.toolbars = toolbarsNormal;
                break;
        }

        this.editor = UE.getEditor("editor", this.editorConfig); // 初始化UE
        this.bindEvent();

    },
    methods: {
        bindEvent: function() {
            var self = this;
            this.editor.addListener("ready", function() {
                if (self.content) {
                    self.editor.setContent(self.content); // 确保UE加载完成后，放入内容。
                }

            });
            this.editor.addListener('afterinsertimage', function(ret) {
                self.getRemovedImg();
            });

            this.editor.addListener("contentChange", function() {
                if (self.editor.key != self.name) return;
                var Intro = self.editor.getContentTxt();
                //编辑器返回的结果
                var result = {
                    ContentTxt: Intro,
                    ContentHtml: self.getUEContent()
                }
                self.$emit("on-content-change", result);
            })
        },
        getUEContent() {
            // 获取内容方法
            var result = {
                ContentTxt: this.editor.getContentTxt(),
                ContentHtml: this.getContentHtml(),
                LastExistImg: this.getLastExistImg(),
                RemovedImg: this.getRemovedImg()
            }

            return result;
        },

        getContentHtml:function(){
             var contentHtml = this.editor.getContent();
             var newContent=$('<div>' + this.editor.getContent() + '</div>');
              newContent.find("[name='uploadImg']").each(function() {
               var src="{StaticUrl}" + $(this).attr('src');
               $(this).attr('src',src);
            });
            newContent.find("[name='onlineImg']").each(function() {
               var src="{StaticUrl}" + $(this).attr('src');
               $(this).attr('src',src);
            });
            return newContent.html();
        },

        getLastExistImg() {
            var LastExistImgList = []; //最终提交的文件
             var newContent=$('<div>' + this.editor.getContent() + '</div>');
            $(newContent).find("[name='uploadImg']").each(function() {
                LastExistImgList.push($(this).attr('src'));
            });
             $(newContent).find("[name='onlineImg']").each(function() {
                LastExistImgList.push($(this).attr('src'));
            });
            return LastExistImgList;
        },

        getRemovedImg() {
            var LastExistImgs = this.getLastExistImg();
            if (this.PreLastExistImg.length > 0) {
                var LastExistImgstr = LastExistImgs.join(',');
                for (var i = 0; i < this.PreLastExistImg.length; i++) {
                    if (this.PreLastExistImg[i] != "") {
                        if (LastExistImgstr.indexOf(this.PreLastExistImg[i]) < 0) {
                            this.RemovedImgList.push(this.PreLastExistImg[i]);
                        }
                    }
                }
            }
            this.PreLastExistImg = JSON.parse(JSON.stringify(LastExistImgs));
            return this.RemovedImgList;
        }

    },
    destroyed: function() {
        this.editor.destroy();
    }
};
</script>

<style scoped>

</style>